library(tidyverse) # for data cleaning and plotting
## Warning: package 'tidyverse' was built under R version 4.0.5
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.3 v purrr 0.3.4
## v tibble 3.1.1 v dplyr 1.0.6
## v tidyr 1.1.3 v stringr 1.4.0
## v readr 1.4.0 v forcats 0.5.1
## Warning: package 'ggplot2' was built under R version 4.0.5
## Warning: package 'tibble' was built under R version 4.0.5
## Warning: package 'tidyr' was built under R version 4.0.5
## Warning: package 'purrr' was built under R version 4.0.4
## Warning: package 'dplyr' was built under R version 4.0.5
## Warning: package 'forcats' was built under R version 4.0.5
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(lubridate) # for date manipulation
## Warning: package 'lubridate' was built under R version 4.0.5
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(openintro) # for the abbr2state() function
## Warning: package 'openintro' was built under R version 4.0.5
## Loading required package: airports
## Warning: package 'airports' was built under R version 4.0.5
## Loading required package: cherryblossom
## Warning: package 'cherryblossom' was built under R version 4.0.5
## Loading required package: usdata
## Warning: package 'usdata' was built under R version 4.0.5
library(palmerpenguins)# for Palmer penguin data
## Warning: package 'palmerpenguins' was built under R version 4.0.5
library(maps) # for map data
##
## Attaching package: 'maps'
## The following object is masked from 'package:purrr':
##
## map
library(ggmap) # for mapping points on maps
## Warning: package 'ggmap' was built under R version 4.0.5
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(gplots) # for col2hex() function
## Warning: package 'gplots' was built under R version 4.0.5
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
## Warning: package 'sf' was built under R version 4.0.5
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(leaflet) # for highly customizable mapping
## Warning: package 'leaflet' was built under R version 4.0.5
library(carData) # for Minneapolis police stops data
library(ggthemes) # for more themes (including theme_map())
## Warning: package 'ggthemes' was built under R version 4.0.5
theme_set(theme_minimal())
# Starbucks locations
Starbucks <- read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv")
##
## -- Column specification --------------------------------------------------------
## cols(
## Brand = col_character(),
## `Store Number` = col_character(),
## `Store Name` = col_character(),
## `Ownership Type` = col_character(),
## `Street Address` = col_character(),
## City = col_character(),
## `State/Province` = col_character(),
## Country = col_character(),
## Postcode = col_character(),
## `Phone Number` = col_character(),
## Timezone = col_character(),
## Longitude = col_double(),
## Latitude = col_double()
## )
starbucks_us_by_state <- Starbucks %>%
filter(Country == "US") %>%
count(`State/Province`) %>%
mutate(state_name = str_to_lower(abbr2state(`State/Province`)))
# Lisa's favorite St. Paul places - example for you to create your own data
favorite_stp_by_lisa <- tibble(
place = c("Home", "Macalester College", "Adams Spanish Immersion",
"Spirit Gymnastics", "Bama & Bapa", "Now Bikes",
"Dance Spectrum", "Pizza Luce", "Brunson's"),
long = c(-93.1405743, -93.1712321, -93.1451796,
-93.1650563, -93.1542883, -93.1696608,
-93.1393172, -93.1524256, -93.0753863),
lat = c(44.950576, 44.9378965, 44.9237914,
44.9654609, 44.9295072, 44.9436813,
44.9399922, 44.9468848, 44.9700727)
)
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
##
## -- Column specification --------------------------------------------------------
## cols(
## date = col_date(format = ""),
## state = col_character(),
## fips = col_character(),
## cases = col_double(),
## deaths = col_double()
## )
Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Mapping data with R” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
ggmap)Starbucks locations to a world map. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization?world <- get_stamenmap(
bbox = c(left = -180, bottom = -57, right = 179, top = 82.1),
maptype = "terrain",
zoom = 2)
## Source : http://tile.stamen.com/terrain/2/0/0.png
## Source : http://tile.stamen.com/terrain/2/1/0.png
## Source : http://tile.stamen.com/terrain/2/2/0.png
## Source : http://tile.stamen.com/terrain/2/3/0.png
## Source : http://tile.stamen.com/terrain/2/0/1.png
## Source : http://tile.stamen.com/terrain/2/1/1.png
## Source : http://tile.stamen.com/terrain/2/2/1.png
## Source : http://tile.stamen.com/terrain/2/3/1.png
## Source : http://tile.stamen.com/terrain/2/0/2.png
## Source : http://tile.stamen.com/terrain/2/1/2.png
## Source : http://tile.stamen.com/terrain/2/2/2.png
## Source : http://tile.stamen.com/terrain/2/3/2.png
ggmap(world) +
geom_point(data = Starbucks,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = .5,
size = .1) +
theme_map() +
theme(legend.background = element_blank())
## Warning: Removed 1 rows containing missing values (geom_point).
Most Starbucks in the U.S. are ????
starbucks_tc <- Starbucks %>%
filter(Country == "US",
`State/Province` == "MN",
City %in% c("Minneapolis", "St. Paul"))
tc <- get_stamenmap(
bbox = c(left = -93.6, bottom = 44.8, right = -92.8, top = 45.1),
maptype = "terrain",
zoom = 11)
## Source : http://tile.stamen.com/terrain/11/491/735.png
## Source : http://tile.stamen.com/terrain/11/492/735.png
## Source : http://tile.stamen.com/terrain/11/493/735.png
## Source : http://tile.stamen.com/terrain/11/494/735.png
## Source : http://tile.stamen.com/terrain/11/495/735.png
## Source : http://tile.stamen.com/terrain/11/496/735.png
## Source : http://tile.stamen.com/terrain/11/491/736.png
## Source : http://tile.stamen.com/terrain/11/492/736.png
## Source : http://tile.stamen.com/terrain/11/493/736.png
## Source : http://tile.stamen.com/terrain/11/494/736.png
## Source : http://tile.stamen.com/terrain/11/495/736.png
## Source : http://tile.stamen.com/terrain/11/496/736.png
## Source : http://tile.stamen.com/terrain/11/491/737.png
## Source : http://tile.stamen.com/terrain/11/492/737.png
## Source : http://tile.stamen.com/terrain/11/493/737.png
## Source : http://tile.stamen.com/terrain/11/494/737.png
## Source : http://tile.stamen.com/terrain/11/495/737.png
## Source : http://tile.stamen.com/terrain/11/496/737.png
## Source : http://tile.stamen.com/terrain/11/491/738.png
## Source : http://tile.stamen.com/terrain/11/492/738.png
## Source : http://tile.stamen.com/terrain/11/493/738.png
## Source : http://tile.stamen.com/terrain/11/494/738.png
## Source : http://tile.stamen.com/terrain/11/495/738.png
## Source : http://tile.stamen.com/terrain/11/496/738.png
ggmap(tc) +
geom_point(data = starbucks_tc,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = 1,
size = 1) +
theme_map() +
theme(legend.background = element_blank())
It controls how detailed the plot would be.
get_stamenmap() in help and look at maptype). Include a map with one of the other map types.tc_wc <- get_stamenmap(
bbox = c(left = -93.6, bottom = 44.8, right = -92.8, top = 45.1),
maptype = "watercolor",
zoom = 11)
## Source : http://tile.stamen.com/watercolor/11/491/735.jpg
## Source : http://tile.stamen.com/watercolor/11/492/735.jpg
## Source : http://tile.stamen.com/watercolor/11/493/735.jpg
## Source : http://tile.stamen.com/watercolor/11/494/735.jpg
## Source : http://tile.stamen.com/watercolor/11/495/735.jpg
## Source : http://tile.stamen.com/watercolor/11/496/735.jpg
## Source : http://tile.stamen.com/watercolor/11/491/736.jpg
## Source : http://tile.stamen.com/watercolor/11/492/736.jpg
## Source : http://tile.stamen.com/watercolor/11/493/736.jpg
## Source : http://tile.stamen.com/watercolor/11/494/736.jpg
## Source : http://tile.stamen.com/watercolor/11/495/736.jpg
## Source : http://tile.stamen.com/watercolor/11/496/736.jpg
## Source : http://tile.stamen.com/watercolor/11/491/737.jpg
## Source : http://tile.stamen.com/watercolor/11/492/737.jpg
## Source : http://tile.stamen.com/watercolor/11/493/737.jpg
## Source : http://tile.stamen.com/watercolor/11/494/737.jpg
## Source : http://tile.stamen.com/watercolor/11/495/737.jpg
## Source : http://tile.stamen.com/watercolor/11/496/737.jpg
## Source : http://tile.stamen.com/watercolor/11/491/738.jpg
## Source : http://tile.stamen.com/watercolor/11/492/738.jpg
## Source : http://tile.stamen.com/watercolor/11/493/738.jpg
## Source : http://tile.stamen.com/watercolor/11/494/738.jpg
## Source : http://tile.stamen.com/watercolor/11/495/738.jpg
## Source : http://tile.stamen.com/watercolor/11/496/738.jpg
ggmap(tc_wc) +
geom_point(data = starbucks_tc,
aes(x = Longitude, y = Latitude, color = `Ownership Type`),
alpha = 1,
size = 1) +
theme_map() +
theme(legend.background = element_blank())
annotate() function (see ggplot2 cheatsheet).mac <- get_stamenmap(
bbox = c(left = -93.18, bottom = 44.93, right = -93.16, top = 44.94),
maptype = "terrain",
zoom = 16)
## Source : http://tile.stamen.com/terrain/16/15805/23590.png
## Source : http://tile.stamen.com/terrain/16/15806/23590.png
## Source : http://tile.stamen.com/terrain/16/15807/23590.png
## Source : http://tile.stamen.com/terrain/16/15808/23590.png
## Source : http://tile.stamen.com/terrain/16/15805/23591.png
## Source : http://tile.stamen.com/terrain/16/15806/23591.png
## Source : http://tile.stamen.com/terrain/16/15807/23591.png
## Source : http://tile.stamen.com/terrain/16/15808/23591.png
## Source : http://tile.stamen.com/terrain/16/15805/23592.png
## Source : http://tile.stamen.com/terrain/16/15806/23592.png
## Source : http://tile.stamen.com/terrain/16/15807/23592.png
## Source : http://tile.stamen.com/terrain/16/15808/23592.png
ggmap(mac) +
geom_point(aes(x = 44.9379, y = -93.1691),
alpha = 1,
size = 1) +
theme_map() +
annotate(geom = "point", x = 44.9379, y = -93.1691, label = "Macalester College")
## Warning: Ignoring unknown parameters: label
## Warning: Removed 4 rows containing missing values (geom_point).
## Warning: Removed 1 rows containing missing values (geom_point).
geom_map())The example I showed in the tutorial did not account for population of each state in the map. In the code below, a new variable is created, starbucks_per_10000, that gives the number of Starbucks per 10,000 people. It is in the starbucks_with_2018_pop_est dataset.
census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
##
## -- Column specification --------------------------------------------------------
## cols(
## state = col_character(),
## est_pop_2018 = col_double()
## )
starbucks_with_2018_pop_est <-
starbucks_us_by_state %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(starbucks_per_10000 = (n/est_pop_2018)*10000)
dplyr review: Look through the code above and describe what each line of code does.We first read in the data. Because under the state column, each state has an extra dot before the name, we separate the name into a dot and the actual state name and name them accordingly. Then, the dot column is removed, and the state column is replaced with all lower case letters. In the second chunk, the census dataset is combined with the Starbuck dataset; all entries in the Starbuck dataset are kept, and entries in the census dataset with a corresponding state name in the Starbuck dataset are also kept. The last line creates a new variable representing the number of Starbucks per 10,000 population.
states_map <- map_data("state")
starbucks_with_2018_pop_est %>%
filter(state_name != "hawaii" & state_name != "alaska") %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = starbucks_per_10000)) +
geom_point(data = Starbucks %>%
filter(Country == "US") %>%
filter(`State/Province` != "HI" & `State/Province` != "AK"),
aes(x = Longitude, y = Latitude),
size = .05,
alpha = .2,
color = "goldenrod") +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
labs(title = "Starbucks in the US",
caption = "Plot created by Yunyang Zhong")
????
leaflet)Create a data set using the tibble() function that has 10-15 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use tibble(), look at the favorite_stp_by_lisa I created in the data R code chunk at the beginning.
Create a leaflet map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3 (HINT: colorFactor()). Add a legend that explains what the colors mean.
Connect all your locations together with a line in a meaningful way (you may need to order them differently in the original data).
If there are other variables you want to add that could enhance your plot, do that now.
fav_yunyang <- tibble(
place = c("Home", "Macalester College", "Shish",
"Nelson's Ice Cream", "Kbop Korean Bistro", "MOA",
"MIA", "Tasty Pot", "Toppers Pizza", "Legendary Spice"),
long = c(-93.175608887381, -93.16910346799591, -93.17061901621636,
-93.16661014505223, -93.23685437388545, -93.24255980272581,
-93.27349178738028, -93.23563321806229, -93.165863187381, -93.22327937388577),
lat = c(44.940496165449325, 44.93833990834085, 44.94003346667343,
44.9279173987216, 44.982074566055694, 44.856749781435035,
44.958653225483964, 44.981375557267775, 44.93996737805556, 44.97333013850549),
top = c(FALSE, TRUE, FALSE,
FALSE, TRUE, FALSE,
FALSE, FALSE, FALSE, TRUE),
rank = c(4, 1, 7,
5, 2, 9,
10, 6, 8, 3)
) %>%
arrange(rank)
pal <- colorFactor("viridis",
domain = fav_yunyang$top)
leaflet(data = fav_yunyang) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~place,
color = ~pal(top),
weight = 10,
opacity = 1) %>%
addLegend(pal = pal,
values = ~top,
opacity = 0.5,
title = "Top 3 Favorite",
position = "bottomright") %>%
addPolylines(lng = ~long,
lat = ~lat)
This section will revisit some datasets we have used previously and bring in a mapping component.
The data come from Washington, DC and cover the last quarter of 2014.
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}. This code reads in the large dataset right away.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
##
## -- Column specification --------------------------------------------------------
## cols(
## name = col_character(),
## lat = col_double(),
## long = col_double(),
## nbBikes = col_double(),
## nbEmptyDocks = col_double()
## )
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. This time, plot the points on top of a map. Use any of the mapping tools you’d like.map <- Trips %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
filter(!is.na(long) & !is.na(lat)) %>%
group_by(sstation) %>%
mutate(total = n()) %>%
distinct(sstation, .keep_all = TRUE)
pal <- colorNumeric("viridis",
domain = map$total)
leaflet(data = map) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~sstation,
opacity = 1,
color = ~pal(total)) %>%
addLegend(pal = pal,
values = ~total,
opacity = 0.5,
title = "total number of departures",
position = "bottomright")
pal <- colorFactor("viridis",
domain = map$client)
leaflet(data = map) %>%
addTiles() %>%
addCircles(lng = ~long,
lat = ~lat,
label = ~sstation,
color = ~pal(client),
weight = 5,
opacity = 1) %>%
addLegend(pal = pal,
values = ~client,
opacity = 0.5,
title = "client type",
position = "bottomright")
?????
The following exercises will use the COVID-19 data from the NYT.
states_map <- map_data("state")
covid19 %>%
group_by(state, fips) %>%
top_n(n = 1, wt = date) %>%
ungroup() %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = str_to_lower(state),
fill = cases)) +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map()
????????????
covid19 %>%
mutate(state = str_to_lower(state)) %>%
group_by(state, fips) %>%
top_n(n = 1, wt = date) %>%
ungroup() %>%
left_join(census_pop_est_2018,
by = "state") %>%
mutate(cases_per_10000 = cases / est_pop_2018 * 10000) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = str_to_lower(state),
fill = cases_per_10000)) +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map()
covid19 %>%
mutate(state = str_to_lower(state)) %>%
filter(date == "2020-03-25" | date == "2020-07-25" | date == "2020-11-25" | date == "2021-03-25") %>%
left_join(census_pop_est_2018,
by = "state") %>%
mutate(cases_per_10000 = cases / est_pop_2018 * 10000) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = str_to_lower(state),
fill = cases_per_10000)) +
facet_wrap(~date) +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
theme(legend.background = element_blank(), legend.position = "top")
?????????
These exercises use the datasets MplsStops and MplsDemo from the carData library. Search for them in Help to find out more information.
MplsStops dataset to find out how many stops there were for each neighborhood and the proportion of stops that were for a suspicious vehicle or person. Sort the results from most to least number of stops. Save this as a dataset called mpls_suspicious and display the table.mpls_suspicious <- MplsStops %>%
group_by(neighborhood) %>%
mutate(total_stops = n()) %>%
filter(problem == "suspicious") %>%
mutate(pro_sus = n()/total_stops) %>%
distinct(neighborhood, pro_sus, .keep_all = TRUE) %>%
arrange(desc(total_stops))
leaflet map and the MplsStops dataset to display each of the stops on a map as a small point. Color the points differently depending on whether they were for suspicious vehicle/person or a traffic stop (the problem variable). HINTS: use addCircleMarkers, set stroke = FAlSE, use colorFactor() to create a palette.pal <- colorFactor("viridis",
domain = MplsStops$problem)
leaflet(data = MplsStops) %>%
addTiles() %>%
addCircleMarkers(lng = ~long,
lat = ~lat,
label = ~idNum,
color = ~pal(problem),
weight = 0.1,
opacity = 0.1,
radius = 5,
stroke = FALSE) %>%
addLegend(pal = pal,
values = ~problem,
opacity = 0.5,
title = "problem type",
position = "bottomright")
eval=FALSE. Although it looks like it only links to the .sph file, you need the entire folder of files to create the mpls_nbhd data set. These data contain information about the geometries of the Minneapolis neighborhoods. Using the mpls_nbhd dataset as the base file, join the mpls_suspicious and MplsDemo datasets to it by neighborhood (careful, they are named different things in the different files). Call this new dataset mpls_all.mpls_nbhd <- st_read("Minneapolis_Neighborhoods.shp", quiet = TRUE)
mpls_all <- mpls_nbhd %>%
left_join(mpls_suspicious,
by = c("BDNAME" = "neighborhood")) %>%
left_join(MplsDemo,
by = c("BDNAME" = "neighborhood"))
leaflet to create a map from the mpls_all data that colors the neighborhoods by prop_suspicious. Display the neighborhood name as you scroll over it. Describe what you observe in the map.pal <- colorNumeric("viridis",
domain = mpls_all$pro_sus)
mpls_all2 <- mpls_all %>%
distinct(BDNAME, .keep_all = TRUE) %>%
filter(!is.na(pro_sus))
leaflet(data = mpls_all) %>%
addTiles() %>%
addCircleMarkers(lng = ~long,
lat = ~lat,
label = ~BDNAME,
color = ~pal(pro_sus)) %>%
addLegend(pal = pal,
values = ~pro_sus,
opacity = 0.5,
title = "prop_suspicious",
position = "bottomright")
## Warning in validateCoords(lng, lat, funcName): Data contains 1 rows with either
## missing or invalid lat/lon values and will be ignored
?????????
leaflet to create a map of your own choosing. Come up with a question you want to try to answer and use the map to help answer that question. Describe what your map shows.DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?